package com.lgy.controller;

import com.lgy.beans.SellerInfo;
import com.lgy.config.ProjectUrlConfig;
import com.lgy.constant.CookieConstant;
import com.lgy.constant.RedisConstant;
import com.lgy.exception.SellException;
import com.lgy.service.impl.SellerService;
import com.lgy.utils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("seller")
public class SellerUserController extends BaseController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid) throws SellException {
        // openid和数据库的数据匹配
        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
        if (sellerInfo == null) {
            throw new SellException("登录失败，登录信息不正确");
        }
        // 设置token到redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;

        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);

        // 设置token到cookie
        CookieUtils.setCookie(getHttpServletResponse(), CookieConstant.TOKEN, token, "/", CookieConstant.EXPIRE);

        return new ModelAndView(REDIRECT + projectUrlConfig.getSell() + "/sell/seller/order/list");
    }

    @GetMapping("/logout")
    public ModelAndView logout() {
        // 从cookie里查询
        String cookie = CookieUtils.getCookie(getHttpServletRequest(), CookieConstant.TOKEN);

        // 清除redis
        if(!StringUtils.isEmpty(cookie)) {
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie));
        }
        // 清除cookie
        CookieUtils.setCookie(getHttpServletResponse(), CookieConstant.TOKEN, null, 0);
        return new ModelAndView("common/success");
    }
}
